<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="message-center-content">

      <!-- 消息内容区 -->
      <div class="message-area">
          <div class="messages-header">
            <h2>消息中心</h2>
          </div>

          <!-- 系统消息（置顶） -->
          <div class="system-message-section">
            <div class="section-header">
              <h3>系统消息</h3>
              <el-badge :value="unreadSystemMessages" class="unread-badge" />
            </div>
            <div class="message-item" @click="viewAllSystemMessages">
              <div class="message-avatar">
                <el-avatar :size="40" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
              </div>
              <div class="message-content">
                <div class="message-header">
                  <h4 class="message-title">{{ latestSystemMessage.title }}</h4>
                  <span class="message-time">{{ formatTime(latestSystemMessage.time) }}</span>
                </div>
                <p class="message-preview">{{ latestSystemMessage.preview }}</p>
              </div>
              <div class="message-arrow">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
          </div>

          <!-- 用户消息列表 -->
          <div class="user-messages-section">
            <div class="section-header">
              <h3>用户消息</h3>
            </div>
            <div class="messages-list" v-loading="loading">
              <div v-if="chatSessions.length === 0" class="empty-state">
                <el-empty description="暂无聊天记录" />
              </div>
              <div
                  v-for="session in chatSessions"
                  :key="session.sessionId"
                  class="message-item"
                  :class="{ unread: session.unreadCount > 0 }"
                  @click="openChat(session)"
              >
                <div class="message-avatar">
                  <el-avatar :size="40" :src="getOtherUserAvatar(session)" />
                  <div class="online-status online"></div>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <h4 class="message-title">{{ getOtherUserName(session) }}</h4>
                    <span class="message-time">{{ formatTime(session.lastTime) }}</span>
                  </div>
                  <p class="message-preview">{{ session.lastMessage || '暂无消息' }}</p>
                </div>
                <div class="message-unread" v-if="session.unreadCount > 0">
                  <el-badge :value="session.unreadCount" class="unread-badge" />
                </div>
                <div class="message-arrow">
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
  </UserLayout>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { getChatSessions, getTotalUnreadCount, getSystemMessages } from '@/utils/apiService'
import { getUserInfo } from '@/utils/auth'
import chatWebSocket from '@/utils/websocket'
import messageStateManager from '@/utils/messageStateManager'

const router = useRouter()
const activeMenu = ref('messages')
const activeIndex = ref('4')

// 数据状态
const loading = ref(false)
const chatSessions = messageStateManager.chatSessions
const totalUnreadCount = ref(0)
const systemMessages = messageStateManager.systemMessages
const systemUnreadCount = messageStateManager.systemUnreadCount

// 计算未读系统消息数量
const unreadSystemMessages = computed(() => {
  return systemUnreadCount.value
})

// 获取最新的系统消息
const latestSystemMessage = computed(() => {
  if (systemMessages.value.length === 0) {
    return {
      title: '暂无系统消息',
      preview: '您目前没有系统消息',
      time: ''
    }
  }
  const latest = systemMessages.value[0]
  return {
    title: latest.title,
    preview: latest.content,
    time: latest.createTime
  }
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''

  const date = new Date(time)
  const now = new Date()
  const diff = now - date

  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }

  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }

  // 小于1天
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }

  // 小于7天
  if (diff < 604800000) {
    return `${Math.floor(diff / 86400000)}天前`
  }

  // 超过7天显示具体日期
  return date.toLocaleDateString()
}

// 获取系统消息数据
const fetchSystemMessages = async () => {
  try {
    const response = await getSystemMessages({ page: 1, size: 5 })
    console.log('🔍 获取系统消息响应:', response)

    const responseData = response.data
    if (responseData.code === 200 || responseData.code === '200') {
      systemMessages.value = responseData.data.messages || []
      systemUnreadCount.value = responseData.data.unreadCount || 0
      console.log('✅ 获取系统消息成功，共', systemMessages.value.length, '条消息')
    } else {
      console.log('❌ 获取系统消息失败:', responseData)
    }
  } catch (error) {
    console.error('获取系统消息失败:', error)
  }
}

// 获取聊天会话数据
const fetchChatSessions = async () => {
  loading.value = true
  try {
    const response = await getChatSessions()

    console.log('🔍 获取聊天会话响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === 200 || responseData.code === '200') {
      chatSessions.value = responseData.data || []

      // 获取每个会话的未读数量
      for (const session of chatSessions.value) {
        session.unreadCount = 0 // 暂时设为0，后续可以通过API获取
      }

      console.log('✅ 获取聊天会话成功，共', chatSessions.value.length, '个会话')
    } else {
      console.log('❌ 获取聊天会话失败:', responseData)
      ElMessage.error('获取聊天会话失败: ' + (responseData.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取聊天会话失败:', error)
    ElMessage.error('获取聊天会话失败')
  } finally {
    loading.value = false
  }
}

// 加载所有数据
const loadAllData = async () => {
  await Promise.all([
    fetchSystemMessages(),
    fetchChatSessions()
  ])
}

// 获取对方用户名
const getOtherUserName = (session) => {
  const currentUser = getUserInfo()
  if (!currentUser) return '未知用户'

  // 判断当前用户是userId1还是userId2，返回对方的名称
  if (session.userId1 === currentUser.id) {
    return session.user2Name || `用户${session.userId2}`
  } else {
    return session.user1Name || `用户${session.userId1}`
  }
}

// 获取对方用户头像
const getOtherUserAvatar = (session) => {
  const currentUser = getUserInfo()
  if (!currentUser) return '/default-avatar.png'

  // 判断当前用户是userId1还是userId2，返回对方的头像
  if (session.userId1 === currentUser.id) {
    return session.user2Avatar || '/default-avatar.png'
  } else {
    return session.user1Avatar || '/default-avatar.png'
  }
}

// 打开聊天窗口
const openChat = (session) => {
  const currentUser = getUserInfo()
  if (!currentUser) {
    ElMessage.warning('请先登录')
    return
  }

  // 确定对方用户ID
  const otherUserId = session.userId1 === currentUser.id ? session.userId2 : session.userId1
  const otherUserName = getOtherUserName(session)

  // 跳转到聊天页面
  router.push({
    path: '/chat',
    query: {
      userId: otherUserId,
      userName: otherUserName,
      sessionId: session.sessionId,
      houseId: session.houseId
    }
  })
}

// 顶部导航栏跳转
const goToHome = () => {
  router.push('/')
}

const goToSearch = () => {
  router.push('/house/search')
}

const goToPublish = () => {
  router.push('/house/publish')
}

const goToMessages = () => {
  router.push('/message')
}

// 用户命令处理
const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      try {
        const { userLogout } = await import('@/utils/auth')
        await userLogout()
        ElMessage.success('退出登录成功')
        router.push('/login')
      } catch (error) {
        console.error('登出失败:', error)
        // 即使登出API失败，也要清除本地状态并跳转
        ElMessage.success('退出登录成功')
        router.push('/login')
      }
      break
  }
}

// 侧边栏跳转
const goToPublishNew = () => {
  router.push('/house/publish')
}

const goToMyHouses = () => {
  router.push('/house/my-houses')
}

const goToAgentApply = () => {
  router.push('/agent/apply')
}

const goToAgentStatus = () => {
  router.push('/agent/status')
}

const goToAgentHouses = () => {
  router.push('/agent/houses')
}

const goToTenant = () => {
  router.push('/rental/tenant')
}

const goToLandlord = () => {
  router.push('/rental/landlord')
}

const goToAgentRental = () => {
  router.push('/rental/agent')
}

const goToProfile = () => {
  router.push('/profile')
}

// 菜单选择处理
const handleSelect = (key) => {
  switch (key) {
    case '1':
      router.push('/')
      break
    case '2':
      router.push('/house/search')
      break
    case '3':
      router.push('/house/publish')
      break
    case '4':
      router.push('/message')
      break
  }
}

// 查看所有系统消息
const viewAllSystemMessages = () => {
  router.push('/message/system')
}

// 页面初始化
onMounted(async () => {
  await loadAllData()

  // 添加状态更新监听器
  messageStateManager.addStateUpdateCallback(handleStateUpdate)

  // 初始化WebSocket连接
  try {
    await chatWebSocket.connect()
  } catch (error) {
    console.error('WebSocket连接失败:', error)
  }
})

// 处理状态更新
const handleStateUpdate = (update) => {
  console.log('消息状态更新:', update)

  if (update.type === 'system' && update.action === 'new_message') {
    // 有新的系统消息时刷新列表
    fetchSystemMessages()
  }
}

// 页面卸载前清理
onBeforeUnmount(() => {
  // 移除状态更新监听器
  messageStateManager.removeStateUpdateCallback(handleStateUpdate)
})
</script>

<style scoped>
.message-center-container {
  display: flex;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

/* 精美的动态背景 */
.dynamic-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

.building-1 {
  left: 10%;
  width: 80px;
  height: 300px;
  animation: buildingGlow 4s infinite alternate;
}

.building-2 {
  left: 25%;
  width: 120px;
  height: 400px;
  animation: buildingGlow 5s infinite alternate-reverse;
}

.building-3 {
  left: 45%;
  width: 100px;
  height: 350px;
  animation: buildingGlow 6s infinite alternate;
}

.building-4 {
  left: 65%;
  width: 140px;
  height: 450px;
  animation: buildingGlow 4.5s infinite alternate-reverse;
}

.building-5 {
  left: 80%;
  width: 90px;
  height: 320px;
  animation: buildingGlow 5.5s infinite alternate;
}

@keyframes buildingGlow {
  0% {
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
  }
  100% {
    box-shadow: 0 -5px 25px rgba(100, 200, 255, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  filter: blur(2px);
}

.cloud-1 {
  top: 20%;
  left: 5%;
  width: 80px;
  height: 30px;
  animation: cloudMove 25s linear infinite;
}

.cloud-2 {
  top: 35%;
  left: 70%;
  width: 120px;
  height: 40px;
  animation: cloudMove 30s linear infinite;
}

.cloud-3 {
  top: 15%;
  left: 40%;
  width: 100px;
  height: 35px;
  animation: cloudMove 35s linear infinite;
}

@keyframes cloudMove {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

/* 太阳 */
.sun {
  position: absolute;
  top: 80px;
  right: 100px;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, #ffeb3b, #ffc107);
  border-radius: 50%;
  box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  animation: sunPulse 3s infinite alternate;
}

@keyframes sunPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 0 60px #ff9800, 0 0 100px #ff5722;
  }
}

/* 光线 */
.light-ray {
  position: absolute;
  top: 120px;
  right: 140px;
  width: 400px;
  height: 200px;
  background: linear-gradient(to right, transparent, rgba(255, 235, 59, 0.2), transparent);
  transform-origin: left center;
  animation: rayRotate 10s infinite linear;
}

.ray-1 {
  transform: rotate(0deg);
  animation-delay: 0s;
}

.ray-2 {
  transform: rotate(60deg);
  animation-delay: 2s;
}

.ray-3 {
  transform: rotate(120deg);
  animation-delay: 4s;
}

@keyframes rayRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 浮动装饰元素 */
.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  right: -80px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

.shape-5 {
  width: 250px;
  height: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-duration: 22s;
  background: radial-gradient(circle, rgba(155, 89, 182, 0.2) 0%, transparent 70%);
}

.shape-6 {
  width: 180px;
  height: 180px;
  top: 70%;
  left: 10%;
  animation-duration: 28s;
  background: radial-gradient(circle, rgba(231, 76, 60, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.message-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  z-index: 1;
  position: relative;
}

.top-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 30px;
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.app-title {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.navbar-center {
  flex: 1;
  margin: 0 20px;
}

:deep(.el-menu--horizontal) {
  border: none;
  background: transparent !important;
}

:deep(.el-menu--horizontal .el-menu-item) {
  color: white;
  border: none;
}

:deep(.el-menu--horizontal .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.el-menu--horizontal .el-menu-item.is-active) {
  color: #4A90E2 !important;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: white;
}

.username {
  font-size: 16px;
  font-weight: 500;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  padding: 20px 0;
  height: 100%;
  box-shadow: 3px 0 10px rgba(0, 0, 0, 0.2);
}

.el-menu-vertical {
  border: none !important;
  height: 100%;
}

.el-menu-item,
.el-sub-menu__title {
  margin: 5px 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.message-area {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.message-area::-webkit-scrollbar {
  width: 8px;
}

.message-area::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.message-area::-webkit-scrollbar-thumb {
  background: rgba(74, 144, 226, 0.6);
  border-radius: 4px;
}

.message-area::-webkit-scrollbar-thumb:hover {
  background: rgba(74, 144, 226, 0.8);
}

.messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.messages-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  margin: 0;
  font-size: 22px;
  color: #2c3e50;
  font-weight: 700;
}

:deep(.unread-badge .el-badge__content) {
  background: #FF6B6B;
}

.system-message-section {
  margin-bottom: 30px;
}

.message-item {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
}

.message-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.message-item.unread {
  border-left-color: #4A90E2;
  background: #f8f9ff;
}

.message-avatar {
  position: relative;
  margin-right: 20px;
}

.online-status {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #ccc;
  border: 2px solid white;
}

.online-status.online {
  background: #50E3C2;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.message-title {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-time {
  font-size: 14px;
  color: #7f8c8d;
}

.message-preview {
  margin: 0;
  font-size: 14px;
  color: #7f8c8d;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.message-unread {
  margin: 0 20px;
}

.message-arrow {
  color: #ccc;
  font-size: 18px;
}

.user-messages-section .message-item {
  margin-bottom: 15px;
}

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .app-title,
  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .messages-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .message-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .message-time {
    align-self: flex-end;
  }
}
</style>
